//test
function islandPerimeter(grid) {
    let m = grid.length, n = grid[0].length;

    for (let row = 0; row < m; row++) {
        for (let col = 0; col < n; col++) {
            if (grid[row][col] === 1) {
                return dfs(row, col);
            };
        };
    };

    function dfs(row, col) {
        if (row < 0 || row >= m || col < 0 || col >= n || grid[row][col] === 0) return 1;       // 越界返回1  

        if (grid[row][col] === 2) {    // 标记访问过的
            return 0;
        };

        grid[row][col] = 2;

        return dfs(row-1,col) + dfs(row+1,col)  + dfs(row,col-1) + dfs(row,col+1) ;
    };



    return 0;
};


const grid = [
    [0,1,0,0],
    [1,1,1,0],
    [0,1,0,0],
    [1,1,0,0]
];

const res = islandPerimeter(grid);

console.log(res);   // 16